package com.atom.mqtt;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class MainActivity extends AppCompatActivity {
    public String uri = "https://open.iot.10086.cn/develop/global/product/#/console" ;
    public String psw = "Was153523.*" ;
    public String Master_APIkey = "ZwAbmwAZiOG6mURx7gGisPE=ulc=";
    public String access_key  = "nBHKXM3OK49RZKG4qMyqkc5dy4/KByJx1FjRm9/nz0c=";
    public String register_id  = "LbxYN3XLrEcIozZJ";
    public String host = "tcp://mqtt.heclouds.com:6002";
    public String userName = "427470";//产品ID
    public String passWord = "was153523";//设备的鉴权信息
    public String clientId = "718887906";//平台的设备ID
    private final static String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    MqttAndroidClient client;
    MqttConnectOptions conOpt;
    private MqttCallback mqttCallback = new MqttCallback() {

        @Override
        public void connectionLost(Throwable cause) {
            Log.e(TAG, "MQTT链接断开:" + cause);
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            String str1 = new String(message.getPayload());
            Log.e(TAG, "topic:" + topic);
            Log.e(TAG, "messageArrived1:" + str1);
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
            Log.e(TAG, "MQTT Complete :" + token.toString());
        }
    };

    private IMqttActionListener listener = new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken asyncActionToken) {
            Log.e(TAG, "MQTT Action onSuccess :" + asyncActionToken.toString());
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            Log.e(TAG, "MQTT Action onFailure :" + asyncActionToken.toString() + " \n" + exception.getLocalizedMessage());
        }
    };

    private void init() {
        client = new MqttAndroidClient(this, host, clientId);
        // 设置MQTT监听并且接受消息
        client.setCallback(mqttCallback);
        conOpt = new MqttConnectOptions();
        // 清除缓存
        conOpt.setCleanSession(true);
        // 设置超时时间，单位：秒
        conOpt.setConnectionTimeout(10);
        // 心跳包发送间隔，单位：秒
        conOpt.setKeepAliveInterval(30);
        // 用户名
        conOpt.setUserName(userName);
        // 密码
        conOpt.setPassword(passWord.toCharArray());
        if (!client.isConnected()) {
            try {
                client.connect(conOpt, null, listener);
            } catch (MqttException e) {
                Log.e(TAG, "mqttConnect fail:" + e.getLocalizedMessage());
            }
        }
    }

    public void mqttSubscribe(String topic) {
        try {
            // 订阅myTopic话题
            client.subscribe(topic, 1);
            Log.e(TAG, "MQTT订阅成功:" + topic);
        } catch (MqttException e) {
            Log.e(TAG, "MQTT订阅失败:" + e.getLocalizedMessage());
        }
    }

    public void mqttPublish(String topic, String msg) {
        Integer qos = 0;
        Boolean retained = false;
        try {
            if (client != null) {
                client.publish(topic, msg.getBytes(), qos.intValue(), retained.booleanValue());
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

}